package com.hao.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
public class test {
    //1 注入rabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testHelloWorld(){
        rabbitTemplate.convertAndSend("spring_queue","hello world spring ......");
    }

    /**
     * 发送fanout消息
     */
    @Test
    public void testFanout(){
        rabbitTemplate.convertAndSend("spring_fanout_exchange","","hello spring fanout ......");
    }
    @Test
    /**
     * 发送direct信息
     */
    public void testDirect(){
        rabbitTemplate.convertAndSend("spring_routing_exchange","info","hello spring direct info ......");
//        rabbitTemplate.convertAndSend("spring_routing_exchange","error","sorry spring direct error ......");
    }

    /**
     * 发送topic
     */
    @Test
    public void testTopic(){
        rabbitTemplate.convertAndSend("spring_topic_exchange","heima.hehe.hh","hello spring topic  ......");
    }

    /**
     * 测试确认信息！
     */

    @Test
    public void testConfirm() throws InterruptedException {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("我来咯confirm~~~");
                if (ack){
                    System.out.println("接收消息成功"+cause);
                }else {
                    System.out.println("接收消息失败"+cause);
                }
            }
        });
        rabbitTemplate.convertAndSend("test_exchange_confirm","confirm","hello spring confirm  ......");
        Thread.sleep(2000);
    }

    /**
     * 测试Return信息
     */
    @Test
    public void testReturn() throws InterruptedException {
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                System.out.println("来咯老弟~~~");
            }
        });

        rabbitTemplate.convertAndSend("test_exchange_confirm","confirm1","hello spring confirm  ......");
        Thread.sleep(2000);
    }

}
